// pages/goods_detail/goods_detail.js
const computedBehavior = require("miniprogram-computed").behavior;

Page({
  behaviors: [computedBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    list: {},
    show: false,
    number: 1,
    totalNum: 0,
  },

  computed: {
    totalNum(data) {
      return data.number * data.list.goods_price;
    },
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({ goods_id }) {
    this.getGoodsDetail(goods_id);
  },
  async getGoodsDetail(id) {
    const { message } = await wx.http({
      url: `/goods/detail?goods_id=${id}`,
    });
    this.setData({
      list: message,
    });
  },
  // 跳转购物车
  onClickIconCart(e) {
    wx.switchTab({
      url: "/pages/cart/cart",
    });
  },
  // 放大轮播图
  showPicture({ mark }) {
    console.log(mark.index);
    wx.previewImage({
      showmenu: true,
      urls: this.data.list.pics.map((v) => v.pics_big),
      current: this.data.list.pics.map((v) => v.pics_big)[mark.index],
    });
  },

  //打开弹窗
  onClickButton() {
    this.setData({
      show: true,
    });
  },
  // 关闭弹窗
  onClose() {
    this.setData({ show: false });
  },
  // 增加减少数量
  onChange({ detail }) {
    this.setData({ number: detail });
  },
  // 加入购物车
  addToCart() {
    const goods = {
      goods_id: this.data.list.goods_id, // 商品的Id
      goods_name: this.data.list.goods_name, // 商品的名称
      goods_price: this.data.list.goods_price, // 商品的价格
      goods_count: this.data.number, // 商品的数量
      goods_small_logo: this.data.list.goods_small_logo, // 商品的图片
      goods_state: true, // 商品的勾选状态
    };
    const cart = wx.getStorageSync("cartList") || [];
    // 如果有相同的商品，则添加数量即可
    cart.forEach((item) => {
      item.goods_id === goods.goods_id
        ? (item.goods_count += goods.goods_count)
        : null;
    });
    // 如果没有重复的商品，则添加进数组
    const result = cart.every((i) => i.goods_id !== goods.goods_id);
    // 去重
    if (result) {
      cart.push(goods);
    }
    wx.setStorageSync("cartList", cart);
    wx.utils.toast("添加成功！");
  },
  // 立即购买
  turnToOrder() {
    wx.navigateTo({
      url: "/pages/order/order",
    });
  },
});
